<script setup>
import { getAllTrademarkAPI, getSpuImageListAPI, getSpuSaleAttrListAPI, getAllSaleAttrAPI, addOrUpdateSpuAPI } from '@/api/product/spu'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'
import { computed } from 'vue'
import { ref } from 'vue'
const emits = defineEmits(['cancel'])

const changeScene = () => {
  emits('cancel', {flag: 0, mode: 'update'})
}

// 定义全部品牌数据
const trademarkList = ref([])

// 定义某个品牌下商品图片数据
const spuImageList = ref([])

// 定义商品销售属性数据
const spuSaleAttr = ref([])

// 定义全部销售属性数据
const allSaleAttrList = ref([])

// 存储已有的spu对象
const spuParams = ref({
  category3Id: '', // 收集的三级分类id
  spuName: '', // spu名称
  description: '', // 描述
  tmId: '', // 品牌id
  spuImageList: [],
  spuSaleAttrList: [],
})

const getSpu = async (row) => {
  // 存储已有的spu对象，将来在模版中展示
  spuParams.value = row
  // 获取全部品牌数据
  const res1 = await getAllTrademarkAPI()
  if(res1.code === 200) {
    trademarkList.value = res1.data
  }
  // 获取某一个品牌下全部商品图片
  const res2 = await getSpuImageListAPI(row.id)
  if(res2.code === 200) {
    spuImageList.value = res2.data.map(item => {
      return {
        // 对返回的图片信息进行格式化，从而被upload组件使用
        name: item.imgName,
        url: item.imgUrl
      }
    })
  }
  // 获取某一品牌商品销售属性
  const res3 = await getSpuSaleAttrListAPI(row.id)
  if(res3.code === 200) {
    spuSaleAttr.value = res3.data
  }
  // 获取全部销售属性
  const res4 = await getAllSaleAttrAPI()
  if(res4.code === 200) {
    allSaleAttrList.value = res4.data
  }
}

// 控制对话框显示隐藏的变量
const dialogVisible = ref(false)

// 存储预览图片的地址
const dialogImageUrl = ref('')

// 照片墙点击预览按钮触发的钩子
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  // 对话框弹出
  dialogVisible.value = true
}

// 照片墙删除触发的钩子
const handleRemove = () => {
  // console.log(123)
}

// 照片上传成功前约束大小和类型
const handlerUpload = (file) => {
  if(file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif') {
    if(file.size/1024/1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件需不大于3M'
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件需为png、jpeg或gif格式'
    })
    return false
  }
}

// 计算出当前spu还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelectArr = allSaleAttrList.value.filter(item => {
    return spuSaleAttr.value.every(item1 => {
      return item.name !== item1.saleAttrName
    })
  })
  return unSelectArr
})

// 收集还未选择的销售属性id和name
const saleAttrIdAndValueName = ref('')

// 添加销售属性的方法
const addSaleAttr = () => {
  // 结构成符合规范的属性
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  // 准备一个新的销售属性对象，将来带给服务器即可
  let newSaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  // 将新的销售对象追加到数组当中
  spuSaleAttr.value.push(newSaleAttr)
  // 清空收集的数据
  saleAttrIdAndValueName.value = ''
}

// 获取属性值输入表单
const saleAttrValueForm = ref([])

// 添加销售属性
const addSaleAttrValue = (row, $index) => {
  row.flag = true
  nextTick(() => {
    saleAttrValueForm.value[$index].focus()
  })
  row.newSaleAttrValue = ''
}

// 属性编辑丢失焦点触发的函数
const toLook = (row) => {
  
  // 整理收集的属性值名字和id
  const { baseSaleAttrId , newSaleAttrValue } = row
  // 整理成服务器需要的属性值格式
  let newSaleAttr = {
    saleAttrValueName: newSaleAttrValue,
    baseSaleAttrId
  }
  // 非法情况判断，空值和重复值
  if(newSaleAttrValue.trim() === '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空'
    })
    return
  }
  let repeat = row.spuSaleAttrValueList.find(item => item.saleAttrValueName === newSaleAttrValue)
  if(repeat) {
    ElMessage({
      type: 'error',
      message: '属性值不能重复'
    })
    return
  }

  // 追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttr)
  // 切换为查看模式
  row.flag = false
}

// 保存spu信息
const save = async () => {
  // 整理参数
  // 1. 整理照片墙数据
  spuParams.value.spuImageList = spuImageList.value.map(item => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url
    }
  })
  // 2. 整理销售属性数据
  spuParams.value.spuSaleAttrList = spuSaleAttr.value
  // 发请求：添加SPU||更新已有SPU
  let res = await addOrUpdateSpuAPI(spuParams.value)
  if(res.code === 200) {
    ElMessage({
      type: 'success',
      message: spuParams.value.id ? '更新成功':'添加成功'
    })
    // 通知父组件切换场景为0
    emits('cancel', {flag: 0, mode: spuParams.value.id ? 'update' : 'add'})
  } else {
    ElMessage({
      type: 'error',
      message: spuParams.value.id ? '更新失败' : '添加失败'
    })
  }
  // 成功
  // 失败
}

// 添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id) => {
  // 清空数据
  Object.assign(spuParams.value, {
    category3Id: '', // 收集的三级分类id
    spuName: '', // spu名称
    description: '', // 描述
    tmId: '', // 品牌id
    spuImageList: [],
    spuSaleAttrList: []
  })
  // 清空照片墙
  spuImageList.value = []
  // 清空销售属性
  spuSaleAttr.value = []
  // 清空选择属性信息
  saleAttrIdAndValueName.value = ''
  // 存储三级分类id
  spuParams.value.category3Id = c3Id
  // 存储品牌信息
  const res1 = await getAllTrademarkAPI()
  if (res1.code === 200) {
    trademarkList.value = res1.data
  }
  // 存储销售属性信息
  const res4 = await getAllSaleAttrAPI()
  if (res4.code === 200) {
    allSaleAttrList.value = res4.data
  }
}

defineExpose({
  getSpu,
  initAddSpu
})
</script>

<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SPU名称" size="default">
        <el-input v-model="spuParams.spuName" placeholder="请你输入SPU名称"/>
      </el-form-item>
      <el-form-item label="SPU品牌" size="default" :inline="true">
        <el-select placeholder="请你选择品牌" style="width: 250px;" v-model="spuParams.tmId">
        <el-option v-for="item in trademarkList" :key="item.id" :value="item.id" :label="item.tmName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" size="default" :inline="true">
        <el-input type="textarea" :rows="2" placeholder="请你输入描述" 
        :maxlength="-1" :show-word-limit="false" :autosize="{ minRows: 2, maxRows: 4 }" v-model="spuParams.description">
        </el-input>
      </el-form-item>
      <el-form-item label="SPU照片" size="default">
        <!-- 
          v-model:file-list 展示默认图片
          action 上传图片的接口地址
          list-type 文件列表的类型
          on-preview 预览按钮钩子
          on-remove 删除按钮钩子
          before-upload 上传前触发的钩子
         -->
        <el-upload
          v-model:file-list="spuImageList"
          action="/api/admin/product/fielUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="handlerUpload"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%;" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU销售属性" size="default">
        <el-select :placeholder="unSelectSaleAttr.length ? `还有${unSelectSaleAttr.length}个未选择` : '无'" style="width: 250px;" v-model="saleAttrIdAndValueName">
          <!-- 利用value收集属性id和name，用：隔开 -->
          <el-option v-for="item in unSelectSaleAttr" :key="item.id" :value="`${item.id}:${item.name}`" :label="item.name"></el-option>
        </el-select>
        <el-button style="margin: 0 10px;" type="primary" icon="Plus" :disabled="!saleAttrIdAndValueName" @click="addSaleAttr">添加销售属性</el-button>

        <el-table border style="margin: 10px 0;" :data="spuSaleAttr">

          <el-table-column label="序号" type="index" width="80" align="center" />
          <el-table-column label="属性名" width="160" prop="saleAttrName"/>

          <el-table-column label="属性值">
            <template #default="{row, $index}">
              <el-tag @close="row.spuSaleAttrValueList.splice($index, 1)" style="margin: 0 5px;" type="primary" size="default" closable v-for="item in row.spuSaleAttrValueList" :key="item.id" >{{ item.saleAttrValueName }}</el-tag>
              <el-input :ref="(el) => saleAttrValueForm[$index] = el" v-if="row.flag === true" v-model="row.newSaleAttrValue" @blur="toLook(row)" placeholder="请输入属性名称" style="width: 100px;" size="small"/>
              <el-button v-else @click="addSaleAttrValue(row, $index)" type="primary" size="small" icon="Plus"></el-button>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="160">
            <template #default="{ $index}">
              <el-button type="danger" size="default" icon="Delete" @click="spuSaleAttr.splice($index, 1)"></el-button>
            </template>
          </el-table-column>
        
        </el-table>
        
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="save">保存</el-button>
        <el-button type="primary" size="default" @click="changeScene">取消</el-button>
      </el-form-item>
    </el-form>
    
  </div>
</template>

<style scoped>

</style>